package cn.com.fattiger.framework.cms.util;

import org.springframework.jdbc.core.RowMapper;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 通用rowmapper类
 * 通过反射将sql语句返回别名于实体类中的field对应，封装返回对象
 * sql:
 * select col1 as a,col2 as b from xxxxx where xxxx
 * class:
 * class O {private String a,private String b; setxxx,getxxx}
 * <p/>
 * Created by Administrator on 2016/2/24.
 */
public class BasicRowMapper<T> implements RowMapper {

    private Class<T> clazz;

    public BasicRowMapper(Class clazz) {
        this.clazz = clazz;
    }

    @Override
    public T mapRow(ResultSet rs, int i) throws SQLException {
        try {
            T obj = clazz.newInstance();
            int columns = rs.getMetaData().getColumnCount();
            for (int idx = 1; idx <= columns; idx++) {
            	if (idx>columns) {
					continue;
				}
                String label = rs.getMetaData().getColumnLabel(idx);
                String fieldName="";
                String[] arr= label.split("_");
                for (int j = 0; j < arr.length; j++) {
					String s= arr[j];
					if (j>0) {
						s = arr[j].substring(0, 1).toUpperCase() + arr[j].substring(1, arr[j].length());
					}
					 fieldName=fieldName+s;
				}
               
                Field field = clazz.getDeclaredField(fieldName);
                if (null != field) {
                    Method method = clazz.getDeclaredMethod("set" + StringUtil.toUpperCaseFirst(fieldName), field.getType());
                    if (null != method) {
                        method.invoke(obj, new Object[]{rs.getObject(idx)});
                    }
                }
            }
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
